package com.xms.configuration.api.controller;


import com.xms.configuration.api.model.NameValueModel;
import com.xms.configuration.api.model.SaveUserCustomizationModel;
import com.xms.configuration.entity.Usercustomization;
import com.xms.configuration.service.IUserCustomizationService;
import com.xms.utils.CollectionUtil;
import com.xms.utils.JsonUtil;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author migo
 * @since 2021-11-13
 */
@RestController
@RequestMapping("/{org}/api/usercustomization")
public class UserCustomizationController extends ApiBaseController {
    private IUserCustomizationService _userCustomizationService;

    @Autowired
    public UserCustomizationController(IUserCustomizationService userCustomizationService) {
        _userCustomizationService = userCustomizationService;
    }

    @ApiOperation("获取用户参数")
    @GetMapping("getbyname/{name}")
    public JsonResultObject getbyname(@PathVariable(value = "name", required = true) String name) {
        Usercustomization result = _userCustomizationService.getByName(_currentUser.getUser().SystemUserId, name);

        return result != null ? JOk(result.getValue()) : JOk();
    }

    @ApiOperation("保存单个用户参数")
    @PostMapping("savebyname")
    public JsonResultObject savebyname(@RequestBody NameValueModel model) {
        if (model == null || StringUtil.isEmpty(model.name)) {
            return JNotSpecifiedParams("name");
        }
        Usercustomization entity = new Usercustomization();
        entity.setUsercustomizationid(UUIDUtil.get());
        entity.setOwnerid(_currentUser.getUser().SystemUserId);
        entity.setName(model.name);
        entity.setValue(JsonUtil.toJSONString(model.value));
        _userCustomizationService.save(entity);
        return JSaveSuccess();
    }

    @ApiOperation("保存多个用户参数")
    @PostMapping("save")
    public JsonResultObject save(@RequestBody SaveUserCustomizationModel model) {
        if (CollectionUtil.isEmpty(model.data)) {
            return JNotSpecifiedParams("data");
        }
        for (NameValueModel item : model.data) {
            Usercustomization entity = new Usercustomization();
            entity.setUsercustomizationid(UUIDUtil.get());
            entity.setOwnerid(_currentUser.getUser().SystemUserId);
            entity.setName(item.name);
            entity.setValue(JsonUtil.toJSONString(item.value));
            _userCustomizationService.save(entity);
        }
        return JSaveSuccess();
    }
}
